package org.apache.ofbiz.extend.util.backup;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.ofbiz.base.util.UtilValidate;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrBuilder;

public class BackupKit {

	/**
     * 获取备份文件信息
     *
     * @param dir dir
     * @return List
     */
    public static List<BackupDto> getBackUps(String basedir,String workDir,String targetDir) {
    	if(UtilValidate.isEmpty(basedir)){
    		basedir = System.getProperties().getProperty("user.home");
    	}else{
    		if (basedir.endsWith("/")) basedir = basedir.substring(0, basedir.length()-1);
    	}
        final StrBuilder srcPathStr = new StrBuilder(basedir);
        if (!workDir.startsWith("/")) workDir = "/" + workDir;
        if (!workDir.endsWith("/")) workDir = workDir + "/";
        srcPathStr.append(workDir);
        if (targetDir.startsWith("/")) targetDir = targetDir.substring(1, targetDir.length());
        srcPathStr.append(targetDir);
        String finalPath = srcPathStr.toString().replace('\\', '/');
        final File srcPath = new File(finalPath);
        final File[] files = srcPath.listFiles();
        final List<BackupDto> backupDtos = new ArrayList<>();
        BackupDto backupDto = null;
        // 遍历文件
        if (null != files) {
            for (File file : files) {
                if (file.isFile()) {
                    if (".DS_Store".equals(file.getName())) {
                        continue;
                    }
                    backupDto = new BackupDto();
                    backupDto.setFileName(file.getName());
                    backupDto.setCreateAt(getCreateTime(file.getAbsolutePath()));
                    backupDto.setFileType(FileUtil.getType(file));
                    backupDto.setFileSize(parseSize(file.length()));
                    backupDto.setBackupType(targetDir);
                    backupDtos.add(backupDto);
                }
            }
        }
        return backupDtos;
    }
    
	 /**
     * 导出为文件
     *
     * @param data     内容
     * @param filePath 保存路径
     * @param fileName 文件名
     */
    public static void postToFile(String data, String filePath, String fileName) throws IOException {
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            final File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            fileWriter = new FileWriter(file.getAbsoluteFile() + "/" + fileName, true);
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bufferedWriter) {
                bufferedWriter.close();
            }
            if (null != fileWriter) {
                fileWriter.close();
            }
        }
    }
    
    /**
     * 获取文件创建时间
     *
     * @param srcPath 文件绝对路径
     * @return 时间
     */
    public static Date getCreateTime(String srcPath) {
        final Path path = Paths.get(srcPath);
        final BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        BasicFileAttributes attr;
        try {
            attr = basicview.readAttributes();
            final Date createDate = new Date(attr.creationTime().toMillis());
            return createDate;
        } catch (Exception e) {
            e.printStackTrace();
        }
        final Calendar cal = Calendar.getInstance();
        cal.set(1970, 0, 1, 0, 0, 0);
        return cal.getTime();
    }

    /**
     * 获取文件长和宽
     *
     * @param file file
     * @return String
     */
    public static String getImageWh(File file) {
        try {
            final BufferedImage image = ImageIO.read(new FileInputStream(file));
            return image.getWidth() + "x" + image.getHeight();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    /**
     * 转换文件大小
     *
     * @param size size
     * @return String
     */
    public static String parseSize(long size) {
        if (size < CommonParamsEnum.BYTE.getValue()) {
            return size + "B";
        } else {
            size = size / 1024;
        }
        if (size < CommonParamsEnum.BYTE.getValue()) {
            return size + "KB";
        } else {
            size = size / 1024;
        }
        if (size < CommonParamsEnum.BYTE.getValue()) {
            size = size * 100;
            return size / 100 + "." + size % 100 + "MB";
        } else {
            size = size * 100 / 1024;
            return size / 100 + "." + size % 100 + "GB";
        }
    }
    
    /*public static void main(String[] args) {
    	List<BackupDto> list = BackupKit.getBackUps("C:/Users/YUANPF/", "/halo/backup/", "/databases/");
    	System.out.println(list.size());
	}*/
}
